package com.itheima.controller;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public String login(User user, HttpServletRequest request) {
        try {
            String usercode = request.getParameter("user_input_verifyCode").trim();
            String correctcode = (String) request.getSession().getAttribute("verifyCodeValue");

            if (usercode == null || usercode.isEmpty()) {
                request.setAttribute("msg", "验证码为空，请输入验证码");
                return "forward:/admin/login.jsp";
            }

            if (usercode.equals(correctcode)) {
                User u = userService.login(user);
                if (u != null) {
                    request.getSession().setAttribute("USER_SESSION", u);
                    return "redirect:/admin/main.jsp";
                } else {
                    request.setAttribute("msg", "用户名或密码错误");
                    return "forward:/admin/login.jsp";
                }
            } else {
                request.setAttribute("msg", "验证码错误");
                return "forward:/admin/login.jsp";
            }
        } catch (Exception e) {
            request.setAttribute("msg", "系统错误: " + e.getMessage());
            return "forward:/admin/login.jsp";
        }
    }
    @RequestMapping("/tomain")
    public String tomain(){
        return "main";
    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        try {
            HttpSession session = request.getSession();
            session.invalidate();
            return "forward:/admin/login.jsp";
        }catch (Exception e){
            e.printStackTrace();
            request.setAttribute("msg","系统错误");
            return "forward:/admin/login.jsp";
        }
    }

}